#coding:utf-8
'''
create on 2017-04-20
@author:sandy
'''
import logging
from pycommon import Const
from pycommon import Pack as packet
import Center
import CenterBuild
import ClientFactory
from pycommon import RedisDb,Utils,Const
import ClientBuild
import CounterManager

def cmdLogin(client,pkt):
    uid, session = packet.unpack("Is", pkt)
    logging.debug("uid = %d,session = %s",uid,session)
    def getSessionCbk(redisSession):
        md5session = Utils.md5sumhex(str(uid)+"USERSESSION"+session)
        if redisSession == md5session:
            client.onLogin(uid,session)
            ClientFactory.instance.mapClient(uid,client)
            client.sendPacket(ClientBuild.loginGate(Const.ERR_OK))
            CounterManager.instance.addCount(Const.COUNTER_LOGIN)
            logging.debug(u"login gate sucess uid = %d session = %s",uid,session)
        else:
            client.sendPacket(ClientBuild.loginGate(Const.ERR_SESSION_WRONG))
            logging.debug(u"login gate failed uid = %d session = %s",uid,session)
    RedisDb.instance.getUserSession(uid,getSessionCbk)

__cmdTable = {
        Const.CMD_C2GATE_LOGIN                : cmdLogin,
    }

def parse(client,cmd,pkt):
    logging.debug("client->gate cmd=%d",cmd)
    if not client.isLogined() and cmd != Const.CMD_C2GATE_LOGIN:
        logging.warn(u"not logined, cmd=%d" % cmd)
        return
    if cmd > Const.CMD_C2CT_BEGIN and cmd < Const.CMD_C2CT_END:
        logging.debug(u"Gate transPkt to Center uid = %d cmd = %d",client.getUid(),cmd)
        Center.instance.sendPacket(CenterBuild.transPackToCenter(client.getUid(),client.getId(),cmd,pkt))
        return
    if cmd > Const.CMD_C2GAME_BEGIN and cmd < Const.CMD_C2GAME_END:
        pass
    
    func = __cmdTable.get(cmd)
    if not func:
        logging.error("cmd = %d not found",cmd);
    
    func(client,pkt)

if __name__ == "__main__":
    pass